package viroyal.com.base.widget.BannerView;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.Scroller;

import java.lang.reflect.Field;
import java.util.List;

import viroyal.com.base.R;
import viroyal.com.base.model.Announced;

public class BannerView {
  private Context context;
  private ViewPager viewPager;
  /** 页面滚动时间 */
  private final int SCROLL_TIME = 400;
  private View bannerView;
  private List<Announced> announcedList;
  private String TAG = getClass().getSimpleName();

  public ViewPager getViewPager() {
    return viewPager;
  }

  public BannerView(Context context, List<Announced> mNoticesList, int layout){
    this.context = context;
    this.announcedList = mNoticesList;
    bannerView = LayoutInflater.from(context).inflate(layout,null);
    initView();
  }

  private void initView() {
    viewPager = bannerView.findViewById(R.id.viewPager);
    //设置默认viewpager当前项
    viewPager.setCurrentItem(announcedList.size()* Integer.MAX_VALUE/2);
    viewPager.setOffscreenPageLimit(1);
    setViewPagerDuration();
  }

  private void setViewPagerDuration() {
    try {
      Field field = ViewPager.class.getDeclaredField("mScroller");
      field.setAccessible(true);
      field.set(viewPager,getScroller(SCROLL_TIME));
    } catch (NoSuchFieldException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
  }

  private Scroller getScroller(final int smoothDuration){
    Scroller scroller = new Scroller(context,new AccelerateInterpolator()){
      @Override
      public void startScroll(int startX, int startY, int dx, int dy, int duration) {
        super.startScroll(startX, startY, dx, dy, smoothDuration);
      }
    };
    return scroller;
  }

  public View getBannerView(){
    return bannerView;
  }
}
